﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LogControl.cs" company="">
//   
// </copyright>
// <summary>
//   The log control.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Systemathics.FrameWork;
using Systemathics.UserControls.Properties;
using Timer=System.Windows.Forms.Timer;

namespace Systemathics.UserControls
{
    /// <summary>
    /// The log control.
    /// </summary>
    [ToolboxBitmap(typeof (LogControl), "UserControlsIcon.bmp")]
    public sealed partial class LogControl : UserControl
    {
        private readonly Timer ElapsedTime;
        private readonly StreamWriter Tracer;
        private readonly SynchronizationContext synchronizationContext;
        private readonly SendOrPostCallback pLogInvokeMethod, pDeleteRows;
        private int Count;
        private RemotingLogServer m_RemotingServer;
        private DateTime StartedTime;
        
        public LogControl()
        {
            InitializeComponent();
            Dock = DockStyle.Fill;
            DoubleBuffered = true;

            LockToolStripButton.CheckOnClick = true;
            LockToolStripButton.Checked = true;
            string dateFile = DateTime.Today.Date.ToShortDateString().Replace("/", string.Empty) + "_" + Time.Now.TimeOfDay.ToString().Replace(":", string.Empty);
            string log = GlobalVariables.LOGS + "\\" + dateFile + ".log";
            synchronizationContext = SynchronizationContext.Current;
            pLogInvokeMethod = new SendOrPostCallback(LogInvokeMethod);
            pDeleteRows = new SendOrPostCallback(RemoveAll);
            ElapsedTime = new Timer {Interval = 1000};
            ElapsedTime.Tick += ElapsedTimeTick;

            try
            {
                Tracer = new StreamWriter(log, false) {AutoFlush = true};
            }
            catch (IOException)
            {
                return;
            }
        }

        private void LogControl_Load(object sender, EventArgs e)
        {
            Dock = DockStyle.Fill;
            if (ParentForm != null)
            {
                ParentForm.Name = "Log";
                ParentForm.Icon = Icon.FromHandle(Resources.En_ligne.GetHicon());
                ParentForm.ShowIcon = true;
                ParentForm.SizeGripStyle = SizeGripStyle.Hide;
                ParentForm.MaximizeBox = true;
                ParentForm.MinimizeBox = true;
                ParentForm.StartPosition = FormStartPosition.CenterScreen;
                ParentForm.FormBorderStyle = FormBorderStyle.Sizable;
                ParentForm.ControlBox = true;
                ParentForm.Opacity = 0.9;
            }
        }
        public void Start()
        {
            m_RemotingServer = new RemotingLogServer();
            if (m_RemotingServer.LogMessage != null)
            {
                m_RemotingServer.LogMessage.OnMessageReceived += RemotingServerRemotingServerEvent;
                ElapsedTime.Start();
                StartedTime = Time.Now;
            }
        }
        public void Stop()
        {
            if (ElapsedTime.Enabled)
                ElapsedTime.Stop();

            if (m_RemotingServer.LogMessage != null)
                m_RemotingServer.LogMessage.OnMessageReceived -= RemotingServerRemotingServerEvent;
        }
        private void ElapsedTimeTick(object sender, EventArgs e)
        {
            TimeSpan difference = Time.Now - StartedTime;
            TimerLabel.Text = difference.Hours.ToString("d2") + ":" + difference.Minutes.ToString("d2") + ":";
            TimerLabel.Text += difference.Seconds.ToString("d2");
        }
        private void RemotingServerRemotingServerEvent(object sender, FireMessageEventArgs e)
        {
            if (IsHandleCreated)
                synchronizationContext.Post(pLogInvokeMethod , e);
        }
        private void LogInvokeMethod(Object obj)
        {
            var e = obj as FireMessageEventArgs;
            MonitorDataGridView.Rows.Add(new[] {e.Time.ToString(), e.Message});
            Count++;
            CountoolStripLabel.Text = Count.ToString();
            if (LockToolStripButton.CheckState == CheckState.Checked)
            {
                MonitorDataGridView.FirstDisplayedScrollingRowIndex = MonitorDataGridView.Rows.Count - 1;
                MonitorDataGridView.Rows[MonitorDataGridView.Rows.Count - 1].Selected = true;
            }

            try
            {
                Tracer.WriteLine(e.Time + ":  " + e.Message);
            }
            catch
            {
            }
        }
        private void OpenToolStripButton_Click(object sender, EventArgs e)
        {
            Process.Start(GlobalVariables.LOGS);
        }
        private void toolStripButton_Stop_Click(object sender, EventArgs e)
        {
            try
            {
                // Stop();
                Tracer.Flush();
                Tracer.Close();
                if (ParentForm != null) ParentForm.Close();
            }
            catch (Exception)
            {
            }
        }
        private void DeletetoolStripButton_Click(object sender, EventArgs e)
        {
            if (MonitorDataGridView != null)
                synchronizationContext.Post(pDeleteRows, null);
        }
        private void RemoveAll(Object obj)
        {
            while (MonitorDataGridView.Rows.Count > 0)
                MonitorDataGridView.Rows.RemoveAt(0);
        }
    }
}